<template>
	<view class="manager" :style="{ height: `${windowHeight}px`, width: `${windowWidth}px` }">
		<!-- #ifdef APP-VUE || MP-WEIXIN || H5 -->
		<view class="move-area" :style="{ height: `${windowHeight - topSpaceHeight}px` }" v-for="(status, key) in partStatus" :key="key" v-if="status">
			<view
				v-for="(item, index) in dataList"
				:key="item.guid"
				v-if="index <= number"
				class="move-view"
				:class="{ 'will-change': index <= 1 }"
				@touchend="slide.touchend"
				@tap.stop="tapCard(item)"
				@touchmove="slide.touchMove"
				@touchstart="slide.touchStart"
				:animation="animationData[index]"
				:data-window-size="windowSize"
				:style="{
					transform:
						index < number
							? ` scale(${1 - (1 - scale.x) * index},${1 - (1 - scale.y) * index})  translate(${translate.x * index}px, ${translate.y * index}px)`
							: ` scale(${1 - (1 - scale.x) * (number - 1)},${1 - (1 - scale.y) * (number - 1)})  translate(${translate.x * (number - 1)}px, ${translate.y * (number - 1)}px)`,
					zIndex: `${99999 - item._id}`,
					opacity: index < number ? `${1 - (1 - opacity) * index}` : `${1 - (1 - opacity) * (number - 1)}`
				}"
			>
				<photo-card class="photoCard" :index="index" :card="item" ref="cardBox"></photo-card>
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>
<!-- #ifdef MP-WEIXIN -->
<script src="./wxs/slide.wxs" module="slide" lang="wxs"></script>
<!-- #endif -->
<!-- #ifdef APP-PLUS || H5 -->
<script module="slide" lang="renderjs">

export default {
	data(){
		return {
			touchMoveDistance:100,
			animationTime:150,
			oldTouces:{},
			moveRotate: {
				x: 0,
				y: null
			},
			windowSize: {
				width: 0,
				height: 0
			},
			moveX:0,
			moveY:0,
			animation:false,
			angle:0,
		}
	},
	methods: {
		calcAngleDegrees(x, y) {
			return Math.atan2(y, x) * 180 / Math.PI + 90;
		},
		touchend(e, ins){
			const instance = e.instance;
			const moveX = this.moveX;
			const moveY = this.moveY;
			const angle = this.angle;
			console.log(moveX)
			if (moveX == undefined || Math.abs(moveX) < (375 / this.windowSize.width) * 100) {

				ins.callMethod('cardPositionReset', {
					animationTime: this.animationTime
				})
				instance.setStyle({
					transform: 'translateX(0px) translateY(0px) rotate(0deg) ',
					'-webkit-transform': 'translateX(0px) translateY(0px) rotate(0deg)',
					'transition': 'all linear  ' + this.animationTime + 'ms'
				})
			} else {
				const d = Math.sqrt(moveX * moveX + moveX * moveX);
				const delMoveDistance = this.windowSize.height;
				const y = (moveY * delMoveDistance) / d;
				const x = (moveX * delMoveDistance) / d;
				const transform = 'translateX(' + x + 'px) translateY(' + y + 'px) ';
				instance.setStyle({
					transform: transform,
					'-webkit-transform': transform,
					'transition': 'all linear  ' + this.animationTime + 'ms'
				})
				ins.callMethod('moveDeleteCard', {
					x,
					y,
					angle,
					animationTime:this.animationTime
				})
			}
		},
		touchMove(e, ins){
			const instance = e.instance;
			const state = instance.getState();
			const oldTouces = this.oldTouces;
			const newTouces = e.touches[0];

			//平移
			let moveX = newTouces.clientX - oldTouces.clientX;
			let moveY = newTouces.clientY - oldTouces.clientY;
			this.moveX = moveX;
			this.moveY = moveY;
			this.animation = false;

			//移动图片旋转角度
			const angle = this.calcAngleDegrees(moveX - this.moveRotate.x, moveY - this.moveRotate.y);
			this.angle = angle;

			const d = moveX * moveX + moveY * moveY;
			var ratio = Math.sqrt(d) / this.touchMoveDistance;
			ratio = ratio > 1 ? 1 : ratio;

			//移动card动画
			var transform = 'translateX(' + moveX + 'px) translateY(' + moveY + 'px) rotate(' + angle + 'deg)';
			instance.setStyle({
				transform: transform,
				'-webkit-transform': transform,
				'transition': 'all linear  0ms'

			});

			ins.callMethod('touchAnimationStep', {
				moveX: moveX,
				moveY: moveY,
				angle: angle,
				ratio: ratio
			});
			//触摸中判断
			ins.callMethod('moveJudge', {
				x: moveX,
				y: moveY,
				ratio: ratio
			});
		},
		touchStart(e, ins){
			var instance = e.instance;
			// var state = instance.getState();
			let windowSize = JSON.parse(instance.getDataset().windowSize);
			if (typeof(windowSize) == 'string') {
				windowSize = JSON.parse(windowSize);
			};
			this.windowSize = windowSize;
			this.$set(this.moveRotate,'y',this.windowSize.height)
			this.oldTouces = e.touches[0];
		}
	}
}
</script>
<!-- #endif -->
<script>
import photoCard from '@/components/photo-card/photo-card.vue';
export default {
	components: { photoCard },
	data() {
		return {
			windowHeight: null,
			windowWidth: null,
			topSpaceHeight: null,
			number: 3,
			delMoveDistance: null,
			scale: { x: 0.95, y: 1 },
			translate: { x: 0, y: 8 }, //y下移
			opacity: 1, //透明度，参数范围 0~1
			moveX: 0, //记录移动值
			moveY: 0, //
			touchAnimation: null,
			animationData: {},
			dataList: [],
			delTime: 150,
			cardId: 0,
			windowSize: { width: null, height: null },

			latitude: null,
			longitude: null,
			canAain: true,
			partStatus: {
				A: true,
				B: false
			}
		};
	},

	computed: {
		uidsList: function() {
			const uidsList = [];
			for (let i = 0; i < this.dataList.length; i++) {
				uidsList.push(this.dataList[i].user_id);
			}
			return uidsList;
		}
	},
	beforeMount() {
		this.initView();
	},
	mounted() {
		this.createAnimation();
		uni.getLocation({
			success: res => {
				if (res.errMsg == 'getLocation:ok') {
					this.$u.api.updateLngLat(res.longitude, res.latitude);
				}
			}
		});
		// this.getData();
	},
	onResize() {
		this.initView();
	},
	updated() {
		this.$forceUpdate();
	},
	methods: {
		refreshData() {
			this.dataList = [];
			this.cardId = 0;
			setTimeout(() => {
				this.getData();
			}, 1000);
		},
		initView() {
			const systemInfo = uni.getSystemInfoSync();
			this.windowWidth = systemInfo.windowWidth;
			this.windowHeight = systemInfo.windowHeight;
			this.windowSize = JSON.stringify({ width: this.windowWidth, height: this.windowHeight });
			this.delMoveDistance = systemInfo.windowHeight;
			this.topSpaceHeight = 44 + systemInfo.statusBarHeight;
		},
		createAnimation() {
			//touch移动动画
			this.touchAnimation = uni.createAnimation({
				duration: 0
			});
			//其他卡片移动
			this.moveAnimation = uni.createAnimation({
				duration: 0
			});
			//删除动画
			this.delanimation = uni.createAnimation({
				duration: this.delTime
			});
			//删除时其他card动画
			this.endanimation = uni.createAnimation({
				duration: 200
			});
		},

		//获取数据
		getData() {
			if (this.canAain) {
				this.canAain = false;
				this.$u.api
					.getCoupCardList()
					.then(res => {
						let dataGroup = [];
						const list = res.data.list;
						console.log(list);
						for (var i = 0; i < list.length; i++) {
							const item = list[i];
							this.cardId = this.cardId + 1;
							if (this.uidsList.indexOf(item.user_id) < 0) {
								dataGroup.push({
									_id: Number(this.cardId) + 1,
									guid: this.$u.guid(),
									avatar: item.avatar,
									sex: item.gender,
									city: item.city,
									province: item.province,
									distance: item.distance,
									nickName: item.nickName,
									label: item.label,
									number: 10,
									isVip: item.is_vip == 1,
									age: item.birth_age || item.idcard_age,
									moveX: 0,
									moveY: 0,
									animation: false,
									user_id: item.user_id
								});
							}
						}
						this.dataList.push(...dataGroup);
						setTimeout(() => {
							this.canAain = true;
						}, 100);
					})
					.catch(e => {
						setTimeout(() => {
							this.canAain = true;
						}, 100);
					});
			}
			// let promise = new Promise((resolve, reject) => {
			// 	let dataGroup = [];
			// 	for (var i = 1; i < 6; i++) {

			// 	}
			// 	this.dataList = [...this.dataList, ...dataGroup];
			// 	resolve();
			// });
			// return promise;
		},
		//触摸中判断
		moveJudge(arg) {
			let el = this.$refs.cardBox[0];
			if (arg.x > 20) {
				el.moveRight(arg.ratio);
			} else if (arg.x < -20) {
				el.moveLeft(arg.ratio);
			} else {
				el.moveCenter();
			}
		},
		//卡片位置重置
		cardPositionReset(arg) {
			let cardBox = this.$refs.cardBox[0];
			cardBox.reset();
			setTimeout(() => {
				//清除动画
				this.animationData[0] = this.delanimation.export();
				for (var i = 1; i < this.number; i++) {
					this.animationData[i] = this.moveAnimation.export();
				}
			}, arg.animationTime);
		},
		moveDeleteCard(arg) {
			this.delCard(arg.x, arg.y);
			setTimeout(() => {
				//清除动画
				this.animationData[0] = this.delanimation.export();
				for (var i = 1; i < this.number; i++) {
					this.animationData[i] = this.moveAnimation.export();
				}
				if (this.dataList.length <= this.number) {
					this.getData();
				}
				if (this.partStatus.A) {
					console.log('aaa');
					this.partStatus = { A: false, B: true };
				} else {
					console.log('bbb');
					this.partStatus = { A: true, B: false };
				}
			}, arg.animationTime);
		},
		//删除card时
		delCard(x, y) {
			if (x > 0) {
				console.log(this.dataList[0], '喜欢');
				this.$emit('slideToRight', this.dataList[0]);
			} else {
				console.log(this.dataList[0], '不喜欢');
				this.$emit('slideToLeft', this.dataList[0]);
			}
			this.dataList.splice(0, 1);
		},
		tapCard(item) {
			console.log(item, '点击');
		},
		touchAnimationStep(arg) {
			//其他card动画
			let ratio = arg.ratio;
			let animationData = {};
			for (var i = 1; i < this.number; i++) {
				const diff = i - ratio;
				if (this.scale.x != 1) this.moveAnimation.scaleX(1 - (1 - this.scale.x) * diff);
				if (this.scale.y != 1) this.moveAnimation.scaleY(1 - (1 - this.scale.y) * diff);
				if (this.translate.x != 0) this.moveAnimation.translateX(this.translate.x * diff);
				if (this.translate.y != 0) this.moveAnimation.translateY(this.translate.y * diff);
				this.moveAnimation.step();
				animationData[i] = this.moveAnimation.export();
			}
			this.animationData = animationData;
			//触摸中视图变化
			// this.moveJudge(this.moveX, this.moveY, ratio);
		}
	}
};
</script>

<style lang="scss">
.manager {
	position: relative;
	.move-area {
		width: 100%;
		margin-top: calc(44px + var(--status-bar-height));
		position: absolute;
		display: flex;
		align-items: center;
		justify-content: center;
		.move-view {
			position: absolute;
		}
	}
}

.will-change {
	will-change: transform;
}
</style>
